import time
import psutil
import requests

# 钉钉机器人webhook地址
DINGTALK_WEBHOOK_URL = 'https://oapi.dingtalk.com/robot/send?access_token=your_access_token'

# 关键字
KEYWORD = "test"

def get_memory_usage():
    """获取当前系统内存使用率"""
    return psutil.virtual_memory().percent

def send_dingtalk_message(message):
    """发送钉钉消息"""
    # 确保消息中包含关键字
    message_with_keyword = f"{message}\n{KEYWORD}"
    
    headers = {
        "Content-Type": "application/json"
    }
    data = {
        "msgtype": "text",
        "text": {
            "content": message_with_keyword
        }
    }
    response = requests.post(DINGTALK_WEBHOOK_URL, json=data, headers=headers)
    return response.json()

def monitor_memory_usage(threshold=80):
    """监控内存使用率"""
    memory_usage = get_memory_usage()
    if memory_usage > threshold:
        message = f"警告：服务器内存使用率已超过{threshold}%，当前使用率为{memory_usage:.2f}%"
        response = send_dingtalk_message(message)
        print(f"钉钉消息发送结果: {response}")

if __name__ == "__main__":
    while True:
        monitor_memory_usage()
        # 每隔60秒检查一次
        time.sleep(60)